package com.gxar.marketdelivery.application.query;

import com.gxar.marketdelivery.application.command.IRuleFilter;
import com.gxar.marketdelivery.application.command.IRuleMatcher;
import com.gxar.marketdelivery.application.context.DeliveryContext;
import com.gxar.marketdelivery.shared.model.DeliveryRuleModel;
import com.gxar.marketdelivery.shared.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author nice
 * @version 1.0
 * @created 2023/8/2.
 */
@Slf4j
@Component
public class RuleHandler {

    @Autowired
    protected List<IRuleMatcher> ruleMatchers;
    @Autowired
    protected List<IRuleFilter> ruleFilters;

    protected List<DeliveryRuleModel> filterByMatcher(DeliveryContext context, List<DeliveryRuleModel> ruleModels) {
        if (CollectionUtils.isEmpty(ruleModels)) {
            return Collections.emptyList();
        }
        return ruleModels.stream()
                .filter(ruleModel -> ruleMatchers.stream().allMatch(matcher -> matcher.isMatch(context, ruleModel)))
                .collect(Collectors.toList());
    }

    protected List<DeliveryRuleModel> filterByFilter(DeliveryContext context, List<DeliveryRuleModel> ruleModels) {
        if (CollectionUtils.isEmpty(ruleModels)) {
            return Collections.emptyList();
        }
        for (IRuleFilter ruleFilter : ruleFilters) {
            ruleModels = ruleFilter.filter(context, ruleModels);
            if (CollectionUtils.isEmpty(ruleModels)) {
                break;
            }
        }
        return ruleModels;
    }
}
